package org.suanfaTranning.ST200_Chatpter1_LineTable_HashTable_String.array;

/**
 * @Auther: qingle
 * @Date: 2024/9/11-17:11
 * @Description:
 * @version: 1.0
 */
public class Solution_lengthOfLongestSubstring3 {
	public static int lengthOfLongestSubstring(String s) {
		int maxLen = 0; // 最长子串的长度
		int[] lastIndex = new int[128]; // 存储每个字符最后出现的位置，初始化为-1
		for (int i = 0; i < lastIndex.length; i++) {
			lastIndex[i] = -1;
		}
		int left = 0; // 滑动窗口的左边界
		for (int right = 0; right < s.length(); right++) { // 遍历字符串
			char c = s.charAt(right);
			// 如果字符已经出现过，并且上次出现的位置在当前滑动窗口内
			if (lastIndex[c] >= left) {
				left = lastIndex[c] + 1; // 移动左边界到上次出现位置的右侧
			}
			lastIndex[c] = right; // 更新字符最后出现的位置
			maxLen = Math.max(maxLen, right - left + 1); // 更新最长子串的长度
		}
		return maxLen; // 返回最长子串的长度
	}

		public static void main(String[] args) {
			Solution_lengthOfLongestSubstring3 solution = new Solution_lengthOfLongestSubstring3();
			String input1 = "abcabcbb";
			System.out.println("Input: \"" + input1 + "\", Output: " + Solution_lengthOfLongestSubstring3.lengthOfLongestSubstring(input1));

			String input2 = "bbbbb";
			System.out.println("Input: \"" + input2 + "\", Output: " + Solution_lengthOfLongestSubstring3.lengthOfLongestSubstring(input2));

			String input3 = "pwwkew";
			System.out.println("Input: \"" + input3 + "\", Output: " + Solution_lengthOfLongestSubstring3.lengthOfLongestSubstring(input3));
		}
	}